import axios from 'axios';
import moment from 'moment';
import qs from 'qs';
import bus from "./bus";
import Cookies from "js-cookie";

let isDebug = true;//本地调试是true,是否是发布版本，无论是95测试还是正式，都是false
let isDevCookie = true;//是否是发布95测试环境，true是测试环境，false是正式环境
let loader;
const MEDIA_URL = 'https://media.iquanzhan.com/';
const OUT_FILE_URL = 'https://outfile.iquanzhan.com/';
const NAS_IMAGE_URL = 'https://nas.iquanzhan.com/trafficSystem/';
const QUANZHAN_URL = 'https://devhims.iquanzhan.com/';
const OVERLOAD_URL = 'https://lzoverload.iquanzhan.com/';
let oldServeUrl = isDevCookie ? "https://devhims.iquanzhan.com/" : "https://hims.iquanzhan.com/";
let socketUrl = isDevCookie ? "devhims.iquanzhan.com/" : "hims.iquanzhan.com/";
const busAlarmCodeMap = {
  "0": "硬盘满",
  "1": "硬盘错",
  "5": "视频丢失",
  "6": "告警输入报警",
  "7": "视频遮挡",
  "8": "移动侦测",
  "9": "视频制式不匹配",
  "10": "全局超速报警",
  "10100": "进区域报警",
  "10101": "出区域报警",
  "10105": "偏离线路",
  "10106": "区域内超速报警",
  "10107": "区域内低速报警",
  "10108": "停留超时",
  "10113": "线路限速",
  "40963": "急加速",
  "40964": "急减速",
  "40965": "碰撞",
  "40966": "侧翻",
  "40967": "急左转弯",
  "40968": "急右转弯",
  "10200": "人员不匹配",
  "40962": "驾驶辅助告警",
  "40969": {
    "1": "重度疲劳",
    "2": "打电话",
    "3": "抽烟",
    "4": "吃东西",
    "5": "闲聊",
    "6": "不目视前方",
    "7": "离岗",
    "8": "未系安全带",
    "9": "打哈欠",
    "10": "捡拾物品",
    "11": "遮挡摄像头",
    "12": "未穿工作服"
  },
  "40974": {
    "1": "前向碰撞",
    "2": "车道偏离",
    "3": "盲区检测",
    "4": "车距过近",
    "5": "行人碰撞"
  },
  "41009": {
    "1": "雷达告警（绿）",
    "2": "雷达告警（黄）",
    "3": "雷达告警（红）"
  }
};
const AISH_URL = 'https://aish.iquanzhan.com/';
const AIFILE_URL = 'https://aifile.iquanzhan.com/';

let currentBreadTitle = '';//当前的页面标题
// isDebug || (() => {
//   window.console = {
//     info: () => {
//     },
//     log: () => {
//     },
//     warn: () => {
//     },
//     debug: () => {
//     },
//     error: () => {
//     },
//     assert: () => {
//     },
//   };
// })();

const TokenKey = isDevCookie ? "DEV_HIMS_PMP_SESSION_ID" : "HIMS_PMP_SESSION_ID";//正式环境：HIMS_PMP_SESSION_ID  测试环境：JSESSIONID/DEVHIMS_PMP_SESSION_ID

function getToken() {
  if (isDebug) {
    return Cookies.get(TokenKey);
  }
}

function setToken(token) {
  if (isDebug) {
    Cookies.set(TokenKey, token);
  } else {
    Cookies.set(TokenKey, token, {domain: '.iquanzhan.com'});
  }
}

function removeToken() {
  return Cookies.remove(TokenKey);
}

axios.defaults.timeout = 60 * 1000;
axios.defaults.withCredentials = true;
axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/x-www-form-urlencoded'
  // 'Content-Type': 'application/json;charset=utf-8'
}

axios.interceptors.request.use(config => {
  if (config.url.indexOf('/import') != -1 || config.url.indexOf('/batchImport') != -1
    || config.url.indexOf('submitAssetFile') != -1 || config.url.indexOf('submitProjectFile') != -1
    || config.url.indexOf('ajaxSubmitSafeMonitor') != -1 || config.url.indexOf('ajaxSubmitWaterMonitor') != -1
    || config.url.indexOf('submitGoods') != -1 || config.url.indexOf('ajaxSubmitElectronicFence') != -1 || config.url.indexOf('submitPolicyFile') != -1|| config.url.indexOf('submitMonitor') != -1|| config.url.indexOf('batchBindRouteUser') != -1
  ) {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
  } else {
    if (config.method === 'get' && config.params && config.url.indexOf('?') === -1) {
      config.url = config.url + "?" + qs.stringify(config.params, {arrayFormat: 'indices', allowDots: true});
      config.params = {};
    } else {
      config.data = qs.stringify(config.data, {arrayFormat: 'brackets', allowDots: true}) // 转为formdata数据格式
    }

  }
  return config;
}, error => {
})

axios.interceptors.response.use(config => {
  return config;
}, error => {
})

const dateFormatStr = {
  dateYMDHMS: "YYYY-MM-DD HH:mm:ss",
  dateYMDHM: "YYYY-MM-DD HH:mm",
  dateYMDH: "YYYY-MM-DD HH",
  dateYMD2: "YYYY-MM-DD",
  dateYM: "YYYY-MM",
  dateYMD: "YYYY.MM.DD",
  dateMDHM: "MM-DD HH:mm",
  dateMD: "M月D日",
  dateHM: "HH:mm",
  dateHMS: "HH:mm:ss",
};

const nasScreenUrl = {
  board: NAS_IMAGE_URL + 'screen/board/',
  linze: NAS_IMAGE_URL + 'screen/linze/',
  all: NAS_IMAGE_URL + 'screen/',
  screenProvince:NAS_IMAGE_URL+'screen/province/',
}

const notifyKey = {
  notifyMessage: 'notifyMessage',
  login: 'login',
  loginOut: 'loginOut',
  breadMessage: 'breadMessage',
  themeChange: 'themeChange',
  importRefreshMessage: 'importRefreshMessage',
}


function netRequest(url, params, method, resolve, reject) {
  axios.defaults.withCredentials = true;
  axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  let config = {
    method: method,
    url: (url.indexOf('mediaUrl') !== -1 || url.indexOf('nasUrl') !== -1 || url.indexOf('https') !== -1) ? url : ('/client/' + url),
  };
  if (params == null) params = {};

  if(params.municipalId&&params.municipalId==-2){
    reject(-1);
    hideLoading();
    return; 
  }
  if(params.projectId&&params.projectId==-2){
    reject(-1);
    hideLoading();
    return; 
  }


  // let userStr = localStorage.getIprtem('userInfo');
  // let user = JSON.parse(userStr);
  // if(user){
  //   params.projectId = user.PROJECT_ID;
  // }
  if (params.sort) {//相同接口有不同排序，为了区分，会在warnerList类里面传sort，有sort就直接复制
    params['order[0][column]'] = params.sort;
    params['order[0][dir]'] = 'DESC';
  } else {
    if (url.indexOf('ajaxReshuffleTableList') !== -1) {
      if (method == 'get') {
        params['order[0][column]'] = 2;
        params['order[0][dir]'] = 'ASC';

        params['order[1][column]'] = 5;
        params['order[1][dir]'] = 'ASC';

        params['order[2][column]'] = 4;
        params['order[2][dir]'] = 'ASC';
      }
    } else if (url.indexOf('ajaxSectionTableList') !== -1) {
      if (method == 'get') {
        params['order[0][column]'] = 2;
        params['order[0][dir]'] = 'ASC';

        params['order[1][column]'] = 4;
        params['order[1][dir]'] = 'ASC';
      }
    } else if (url.indexOf('roadPlanTableList') !== -1) {
      if (method == 'get') {
        params['order[0][column]'] = 13;
        params['order[0][dir]'] = 'DESC';
      }
    } else if (url.indexOf('ajaxGoodsTableList') !== -1) {
      if (method == 'get') {
        params['order[0][column]'] = 2;
        params['order[0][dir]'] = 'DESC';

        params['order[0][column]'] = 8;
        params['order[0][dir]'] = 'DESC';
      }
    } else if (url.indexOf('ajaxLandTableList') !== -1) {
      if (method == 'get') {
        params['order[0][column]'] = 0;
        params['order[0][dir]'] = 'ASC';
      }
    } else {
      let tableList = "ajaxEmergencyDrillTableList:3,ajaxAccountTableList:6,ajaxAcoustoTableList:5,ajaxDataTableList:3,ajaxProjectTableList:3,ajaxTapeTableList:3,ajaxVersionTableList:5,ajaxAssessTableList:7,ajaxAssetFileTableList:5,ajaxBayonetTableList:5,ajaxBayoneterTableList:2,ajaxBridgeTableList:0,ajaxBulletinBoardTableList:5,ajaxBusDeviceTableList:7,ajaxBusLineTableList:0,ajaxBusStationTableList:5,ajaxCaseTableList:4,ajaxCheckRecordTableList:7,ajaxCheckpointTableList:10,ajaxCleanRecordTableList:4,ajaxCompanyAssessTableList:0,ajaxAssessTableList:7,ajaxCompanyTableList:10,ajaxContractTableList:9,ajaxCriticismStandardTableList:3,ajaxDepartmentTableList:4,ajaxDriverTableList:2,ajaxDynamicDetailTableList:1,ajaxDynamicPatrolTableList:2,ajaxElectronicFenceTableList:4,ajaxEmergencyDeviceTableList:6,ajaxEmergencyDisposalTableList:3,ajaxEmergencyMaterialTableList:7,ajaxEmergencyPointTableList:3,ajaxEmergencyReserveTableList:3,ajaxEngineProjectTableList:4,ajaxEventTableList:6,ajaxExchangeOrderTableList:4,ajaxFeedWorksheetTableList:3,ajaxFlagRecordTableList:4,ajaxFlagStopTableList:4,ajaxInoutTableList:5,ajaxInspectTableList:8,ajaxIssueTableList:7,ajaxLandTableList:7,ajaxLogTableList:4,ajaxMaintainProjectTableList:8,ajaxMaintainStandardTableList:6,ajaxMeetingTableList:6,ajaxMessageTableList:1,ajaxPatrolTableList:8,ajaxProgramTableList:4,ajaxProjectAssessTableList:3,ajaxProjectFileTableList:6,ajaxReserveSceneTableList:5,ajaxReserveRecordTableList:1,ajaxRfidTableList:4,ajaxRoleTableList:2,ajaxRouteTableList:0,ajaxRouteMonitorTableList:5,ajaxRouteOverviewTableList:5,ajaxRouteMonitorTableList:5,ajaxRouteUserTableList:6,ajaxRouteUserTableList:6,ajaxRouterOfficeTableList:5,ajaxSafeMonitorTableList:0,ajaxSensorTableList:7,ajaxSetupLogsTableList:11,ajaxSideSlopeMonitorTableList:2,ajaxStaticDetailTableList:2,ajaxStaticPatrolTableList:0,ajaxStructureTableList:5,ajaxAssetTableList:6,ajaxVehicleTableList:0,ajaxWaterAlarmTableList:4,ajaxWaterMonitorTableList:4,ajaxHourWaterMonitorDataTableList:0,ajaxWaterMonitorDataStatisticsTableList:0,ajaxWorksheetTableList:9,ajaxWxUserTableList:1,ajaxZhichaoDataTableList:7,ajaxSuperviseTableList:6,ajaxDynamicGroupTableList:0,ajaxPqiTableList:5,ajaxPciTableList:5,ajaxRoughnessTableList:5";
      let list_ = tableList.split(',');

      for (let i = 0; i < list_.length; i++) {
        let itemStrList = list_[i].split(":");

        let tableUrl = itemStrList[0];
        let tableSortIndex = itemStrList[1];
        if (url.indexOf(tableUrl) != -1 && method == 'get') {
          params['order[0][column]'] = Number(tableSortIndex);
          params['order[0][dir]'] = 'DESC';
          break;
        }
      }
    }
  }


  if (method == 'get') {
    config.params = params;
  } else {
    config.data = params;
  }
  config.traditional = true;//必须指定为true
  axios(config)
    .then(function (response) {
      // console.log(url, response);
      hideLoading();
      let data = response.data;

      if (data.errorCode !== null && data.errorCode !== undefined) {
        if (data.errorCode == 0 || data.errorCode == 2) {
          resolve(data);
        } else if (data.errorCode == 401) {
          bus.$emit(notifyKey.notifyMessage, {name: '登录过期，请重新登录'});
          bus.$emit(notifyKey.loginOut);
        } else {
          reject(data);
          bus.$emit(notifyKey.notifyMessage, {name: data.errorMessage});
        }
      } else {
        resolve(data);
      }
    })
    .catch(function (error) {
      // console.log(url, error);
      if (error.status == 1) {
        bus.$emit(notifyKey.notifyMessage, {name: '连接超时'});
      } else {
        if (isDebug)
          bus.$emit(notifyKey.notifyMessage, {name: '网络错误'});
      }
      hideLoading();
      reject(error);

    });
}


function getStatic(url) {
  axios.defaults.withCredentials = false;
  axios.defaults.headers = {}
  return new Promise((resolve, reject) => {
    let config = {
      method: 'get',
      url: url,
      headers: {}
    };
    axios(config)
      .then(function (response) {
        // console.log(url, response, response.data);
        resolve(response.data)
      })
      .catch(function (error) {
        reject(null)
      });
  })

}

function get(url, params, showLoading = true) {
  return new Promise((resolve, reject) => {
    netRequest(url, params, 'get', resolve, reject, showLoading);
  });
}

function post(url, params, showLoading = true) {
  return new Promise((resolve, reject) => {
    netRequest(url, params, 'post', resolve, reject, showLoading);
  });
}

function showToast(msg) {
  // bus.$emit(notifyKey.notifyMessage, {name:msg});
  console.log(msg);
}


function dateFormat(date, formatStr) {
  return moment(date).format(formatStr);
}

function showLoading(context) {
  if (!loader) {
    loader = context.$loading.show({
      container: null,
      canCancel: true,
      loader: 'dots',
      backgroundColor: 'rgba(255,255,255,0)',
      // opacity: 0.7,
      color: 'rgba(0,123,255)',
      width: 78,
      height: 78,
      blur: 0
    });
  }
}

function hideLoading() {
  if (loader) {
    loader.hide();
    loader = null;
  }
}

function isNull(obj) {
  if (null == obj || undefined == obj || obj == "") {
    return true;
  }
  return false;
}

function routeBack(router) {
  if (router.history.current.matched) {
    let matched = router.history.current.matched;
    if (matched.length > 1) {
      router.replace(matched[matched.length - 2].path);
    }
  }
}

function getServeImageUrl(config = null) {
  let systemInfoStr = localStorage.getItem('systemInfo');
  if (systemInfoStr) {
    let systemInfo = JSON.parse(systemInfoStr);
    let url = systemInfo.amsConfig.fileUrl + '/upload/img/';
    if (config) {
      if (config.route) {
        url = systemInfo.amsConfig.fileUrl + '/upload/route/';
      } else if (config.section) {
        url = systemInfo.amsConfig.fileUrl + '/upload/section/';
      } else if (config.file) {
        url = systemInfo.amsConfig.fileUrl + '/upload/file/';
      } else if (config.aiFile) {
        url = systemInfo.amsConfig.aiFile;
      } else if (config.zhichao) {
        url = systemInfo.amsConfig.outUrl + '/upload/overload/';
      }
    }
    return url;
  }
}

function getMenuInfo(menuList, currentRouterPath) {
  let target = null;
  let openKeys = [];
  let names = [];

  a:for (let i = 0; i < menuList.length; i++) {
    let item = menuList[i];
    if (currentRouterPath == item.key) {
      target = item;
      openKeys.push(item.key);//第一层打开的菜单key
      names.push(item.MENU_NAME);//第一层打开的菜单name
      break;
    }
    if (item.CHILD && item.CHILD.length > 0) {
      for (let j = 0; j < item.CHILD.length; j++) {
        let itemItem = item.CHILD[j];

        if (currentRouterPath == itemItem.key) {
          target = itemItem;
          openKeys.push(item.key);//第一层打开的菜单key
          names.push(item.MENU_NAME);//第一层打开的菜单name
          break a;
        }
        if (itemItem.CHILD && itemItem.CHILD.length > 0) {
          for (let k = 0; k < itemItem.CHILD.length; k++) {
            if (currentRouterPath == itemItem.CHILD[k].key) {
              target = itemItem.CHILD[k];

              openKeys.push(item.key);//第一层打开的菜单key
              names.push(item.MENU_NAME);//第一层打开的菜单name

              openKeys.push(itemItem.key);//第二层打开的菜单key
              names.push(itemItem.MENU_NAME);//第二层打开的菜单name
              break a;
            }
          }
        }
      }
    }
  }
  return {
    openKeys: openKeys, names: names, target: target
  }
}

function getTableParams(sizeChange, change, defaultPageSize = 12, pageSizeOptions = ['12', '24']) {
  return {
    current: 1,
    defaultCurrent: 1,  // 默认当前页数
    defaultPageSize: defaultPageSize,   // 默认当前页显示数据的大小
    total: 0, // 总数，必须先有
    showSizeChanger: true,
    pageSizeOptions: pageSizeOptions,
    showTotal: total => `共 ${total} 条`, // 显示总数
    onShowSizeChange: (current, pageSize) => {
      sizeChange(current, pageSize);
    },
    // 改变每页数量时更新显示
    onChange: (current, size) => {
      change(current, size);
    } // 点击页码事件
  }
}

function getTableParamsNoSizeChange(change, defaultPageSize = 3) {
  return {
    current: 1,
    defaultCurrent: 1,  // 默认当前页数
    defaultPageSize: defaultPageSize,   // 默认当前页显示数据的大小
    total: 0, // 总数，必须先有
    showSizeChanger: false,
    showTotal: total => `共 ${total} 条`, // 显示总数
    onChange: (current, size) => {
      change(current, size);
    } // 点击页码事件
  }
}

/**
 * 检测图片是否存在
 * @param url
 */
function imageIsExist(url) {
  return new Promise((resolve) => {
    let img = new Image();
    img.onload = function () {
      if (this.complete == true) {
        resolve(true);
        img = null;
      }
    }
    img.onerror = function () {
      resolve(false);
      img = null;
    }
    img.src = url;//开始加载网络图片，并通过promise回调
  })
}

function setCurrentBreadTitle(val) {
  currentBreadTitle = val;
}

function getCurrentBreadTitle() {
  return currentBreadTitle;
}

function getAdCode() {
  let projectInfoStr = localStorage.getItem('projectInfo');
  if (projectInfoStr) {
    let projectInfo = JSON.parse(projectInfoStr);
    return projectInfo.AD_CODE;
  }
}

function getUserAdCode() {
  let adCode = '';
  let userStr = localStorage.getItem('userInfo');
  let user = JSON.parse(userStr);
  if (user && user.AD_CODE) {
    adCode = user.AD_CODE;
  } else {
    let provinceStr = localStorage.getItem('projectInfo');
    let province = JSON.parse(provinceStr);
    adCode = province.AD_CODE;
  }
  return adCode;
}

function getUserId() {
  let userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    let userInfo = JSON.parse(userInfoStr);
    return userInfo.USER_ID;
  }
}

function getUserName() {
  let userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    let userInfo = JSON.parse(userInfoStr);
    return userInfo.NAME;
  }
}

function getProjectId() {
  let projectInfoStr = localStorage.getItem('projectInfo');
  if (projectInfoStr) {
    let projectInfo = JSON.parse(projectInfoStr);
    return projectInfo.PROJECT_ID;
  }
}

function getDistrictName() {
  let projectInfoStr = localStorage.getItem('projectInfo');
  if (projectInfoStr) {
    console.log(11113,projectInfoStr);
    let projectInfo = JSON.parse(projectInfoStr);
    return projectInfo.DISTRICT_NAME;
  }
}


function getProjectInfo() {
  let projectInfoStr = localStorage.getItem('projectInfo');
  if (projectInfoStr) {
    let projectInfo = JSON.parse(projectInfoStr);
    return projectInfo;
  }
}

function formatSize(bytes) {
  if (bytes === 0) return '0 B';
  let k = 1000, // or 1024
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));

  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

function millis2FitTimeSpan(millis, precision) {
  let seconds = millis;
  if (seconds <= 0 || precision <= 0) {
    return "";
  }
  let days = precision >= 1 ? parseInt((seconds / 60 / 60 / 24)) : 0;
  let hour = precision >= 2 ? parseInt(((seconds - days * 24 * 60 * 60) / 60 / 60)) : 0;
  let min = precision >= 3 ? parseInt(((seconds - hour * 60 * 60 - days * 24 * 60 * 60) / 60)) : 0;
  let second = precision >= 4 ? parseInt((seconds - min * 60 - hour * 60 * 60 - days * 24 * 60 * 60)) : 0;
  let returnStr = "";
  if (days > 0) {
    returnStr += days + "天";
  }
  if (hour > 0) {
    returnStr += hour + "小时";
  }
  if (min >= 0) {
    returnStr += min + "分";
  }
  if (second >= 0) {
    returnStr += second + "秒";
  }
  return returnStr;
}

function vehicleOnline(status) {
  if (status) {
    let status_ = status > -1 && (status & (1 << 2)) == 0;
    return status_;
  } else {
    return false
  }

}

function getMapCenterCodeMap(adCode) {
  let cityCode = (adCode != null && adCode.length > 4) ? adCode.substring(0, 4) : "";
  let districtCode = (adCode != null && adCode.length > 6) ? adCode.substring(0, 6) : "";
  let lastCode = (adCode != null && adCode.length > 6) ? adCode.substring(4, 6) : "";

  if (lastCode == "01") {
    districtCode = adCode.substring(0, 4) + "00";
  }

  let map = {
    centerCode: (districtCode != "" ? districtCode : (cityCode != "" ? cityCode : "")),
    level: (districtCode != "" ? "district" : (cityCode != "" ? "city" : ""))
  };

  return map;
}

function getFileSuffix(fileName) {
  // "xls", "xlsx", "docx", "doc", "pptx", "ppt", "jpg", "png", "bmp", "jpeg", "pdf", "mp4", "txt", "zip", "rar"
  let text = 'T';
  if (fileName.endsWith('.docx') || fileName.endsWith('.doc')) {
    text = 'W';
  } else if (fileName.endsWith('.xls') || fileName.endsWith('.xlsx')) {
    text = 'X';
  } else if (fileName.endsWith('.ppt') || fileName.endsWith('.pptx')) {
    text = 'P';
  } else if (fileName.endsWith('.jpg') || fileName.endsWith('.png') || fileName.endsWith('.jpeg')) {
    text = 'J';
  } else if (fileName.endsWith('.bmp')) {
    text = 'B';
  } else if (fileName.endsWith('.pdf')) {
    text = 'P';
  } else if (fileName.endsWith('.mp4')) {
    text = 'M';
  } else if (fileName.endsWith('.txt')) {
    text = 'T';
  } else if (fileName.endsWith('.zip')) {
    text = 'Z';
  } else if (fileName.endsWith('.rar')) {
    text = 'R';
  }
  return text;
}

function getPageArea(adCode, provinceCallback, cityCallback, districtCallback, townCallback) {
  if (adCode) {
    let provinceCode = (adCode != null && adCode.length > 2) ? adCode.substring(0, 2) + '0000' : '';
    let cityCode = (adCode != null && adCode.length > 4) ? adCode.substring(0, 4) + '00000000' : '';
    let districtCode = (adCode != null && adCode.length > 6) ? adCode.substring(0, 6) + '000000' : '';
    let townCode = (adCode != null && adCode.length > 9) ? adCode.substring(0, 9) + '000' : '';
    // console.log(provinceCode, cityCode, districtCode, townCode);
    get('ajaxRegionList', {level: 'province'}).then((ret) => {
      let list = ret.content;
      for (let i = 0; i < list.length; i++) {
        if (provinceCode == list[i].AD_CODE && provinceCallback) {
          provinceCallback({name: list[i].NAME, adCode: list[i].AD_CODE});
          break;
        }
      }
    });

    get('ajaxRegionList', {parentCode: provinceCode, level: 'city'}).then((ret) => {
      let list = ret.content;
      for (let i = 0; i < list.length; i++) {
        if (cityCode == list[i].AD_CODE && cityCallback) {
          cityCallback({name: list[i].NAME, adCode: list[i].AD_CODE});
          break;
        }
      }
    });

    get('ajaxRegionList', {parentCode: cityCode, level: 'district'}).then((ret) => {
      let list = ret.content;
      for (let i = 0; i < list.length; i++) {
        if (districtCode == list[i].AD_CODE && districtCallback) {
          districtCallback({name: list[i].NAME, adCode: list[i].AD_CODE});
          break;
        }
      }
    });

    get('ajaxRegionList', {parentCode: districtCode, level: 'town'}).then((ret) => {
      let list = ret.content;
      for (let i = 0; i < list.length; i++) {
        if (townCode == list[i].AD_CODE && townCallback) {
          townCallback({name: list[i].NAME, adCode: list[i].AD_CODE});
          break;
        }
      }
    });


  }
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

function json2Url(requestParams) {
  let params = [];
  Object.entries(requestParams).forEach(([key, value]) => {
    let param = key + '=' + value;
    params.push(param);
  });
  return '?' + params.join('&');
}

function isProvince(route) {
  if (route.fullPath.indexOf('/province') !== -1) {
    return true;
  } else {
    return false;
  }
}

function isCity(route) {
  if (route.fullPath.indexOf('/city') !== -1) {
    return true;
  } else {
    return false;
  }
}

function getAreaLevelUrl(route) {
  let baseUrl = '';
  if (isProvince(route)) {
    baseUrl = '/province/'
  } else if (isCity(route)) {
    baseUrl = '/city/'
  }
  return baseUrl;
}

function getProjectLocation() {
  if(getProjectInfo()) {
    let projectId = getProjectInfo().PROJECT_ID;
    if (projectId == 94) {  //临泽
      return [100.164333, 39.15224]
    } else if (projectId == 72){  //江阳
      return [105.449125, 28.861675];
    } else if (projectId == 41) { // 新都
      return [104.138705, 30.833499]
    }
  }
  return [100.164333, 39.15224]
}



function getRouteListJson() {
  return getStatic(NAS_IMAGE_URL + 'screen/config/' + 'route_location_' + getProjectId() + '.json');
}

function getPlateBg(text) {
  let color = '#fff';
  let bgColor = 'linear-gradient(140deg,rgba(28,158,255,1) 0%,rgba(0,145,253,1) 100%)';
  if (text.indexOf('蓝') !== -1) {
    color = '#fff';
    bgColor = 'linear-gradient(140deg,rgba(28,158,255,1) 0%,rgba(0,145,253,1) 100%)';
  } else if (text.indexOf('黄') !== -1) {
    color = 'rgba(99, 49, 28, 1)';
    bgColor = 'linear-gradient(180deg,rgba(252,219,0,1) 0%,rgba(247,181,0,1) 100%)';
  } else if (text.indexOf('绿') !== -1) {
    color = 'rgba(0, 0, 0, 1)';
    bgColor = 'linear-gradient(180deg,rgba(189,229,199,1) 0%,rgba(71,240,93,1) 100%)';
  }
  return {
    color,
    bgColor
  };
}


// private method for UTF-8 encoding
var _utf8_encode = function (string) {
  string = string.replace(/\r\n/g, "\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
    var c = string.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if ((c > 127) && (c < 2048)) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }
  }
  return utftext;
}
// private method for UTF-8 decoding
var _utf8_decode = function (utftext) {
  var string = "";
  var i = 0;
  let c = 0, c1 = 0, c2 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c2 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    } else {
      c2 = utftext.charCodeAt(i + 1);
      c1 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c1 & 63));
      i += 3;
    }
  }
  return string;
}
function getParams(url) {
  try {
    url = url.match(/\?([^#]+)/)[1];
    const obj = {};
    const arr = url.split('&');
    for (let i = 0; i < arr.length; i++) {
      let subArr = arr[i].split('=');
      let key = decodeURIComponent(subArr[0]);
      let value = decodeURIComponent(subArr[1]);
      obj[key] = value;
    }
    return obj;
  } catch (err) {
    return null;
  }
}



let map = null;

function getSelectedRegion(){
  let str = localStorage.getItem('regionInfo');
  if(str){
    let regionInfo = JSON.parse(str);
    return regionInfo;
  }
  return null;
}

function getMapOption(){
  return {
    fillColor: '#58ABE9',
    strokeColor: '#D3EEFE',
    fillColorSelected: '#FFC430',
    strokeColorSelected: '#FFC430',
  }
}

export default {
  get: get,
  post: post,
  showToast: showToast,
  dateFormat: dateFormat,
  dateFormatStr: dateFormatStr,
  eventBus: bus,
  notifyKey: notifyKey,
  showLoading: showLoading,
  hideLoading: hideLoading,
  MEDIA_URL: MEDIA_URL,
  OUT_FILE_URL: OUT_FILE_URL,
  QUANZHAN_URL: QUANZHAN_URL,
  routeBack: routeBack,
  isNull: isNull,
  rootPath: '',
  getServeImageUrl: getServeImageUrl,
  NAS_IMAGE_URL: NAS_IMAGE_URL,
  AISH_URL: AISH_URL,
  AIFILE_URL: AIFILE_URL,
  getToken: getToken,
  setToken: setToken,
  removeToken: removeToken,
  getMenuInfo: getMenuInfo,
  mGrid: {gutter: 24, xxl: 6, xl: 4, lg: 3, md: 2, sm: 2, xs: 1},
  getTableParams: getTableParams,
  getTableParamsNoSizeChange: getTableParamsNoSizeChange,
  imageIsExist: imageIsExist,
  routeTypeList: [
    {ROUTE_TYPE: 'G', ROUTE_TYPE_NAME: '国道'},
    {ROUTE_TYPE: 'S', ROUTE_TYPE_NAME: '省道'},
    {ROUTE_TYPE: 'X', ROUTE_TYPE_NAME: '县道'},
    {ROUTE_TYPE: 'Y', ROUTE_TYPE_NAME: '乡道'},
    {ROUTE_TYPE: 'C', ROUTE_TYPE_NAME: '村道'}
  ],
  setCurrentBreadTitle: setCurrentBreadTitle,
  getCurrentBreadTitle: getCurrentBreadTitle,
  getAdCode: getAdCode,
  getUserAdCode: getUserAdCode,
  getProjectId: getProjectId,
  getUserName: getUserName,
  millis2FitTimeSpan: millis2FitTimeSpan,
  vehicleOnline: vehicleOnline,
  formatSize: formatSize,
  getMapCenterCodeMap: getMapCenterCodeMap,
  busAlarmCodeMap: busAlarmCodeMap,
  getFileSuffix: getFileSuffix,
  getProjectInfo: getProjectInfo,
  getPageArea: getPageArea,
  getBase64: getBase64,
  getUserId: getUserId,
  json2Url: json2Url,
  pileNumberValidity: /(^(K|k)([1-9]{1}\d*)(\+\d{3})?)|(^(K|k)(\d{1})(\+\d{3})?)/,
  oldServeUrl: oldServeUrl,
  isDebug: isDebug,
  nasScreenUrl: nasScreenUrl,
  isProvince: isProvince,
  isCity: isCity,
  getAreaLevelUrl: getAreaLevelUrl,
  socketUrl: socketUrl,
  getProjectLocation: getProjectLocation,
  getStatic: getStatic,
  getRouteListJson: getRouteListJson,
  getPlateBg: getPlateBg,
  OVERLOAD_URL: OVERLOAD_URL,
  getParams:getParams,
  getDistrictName: getDistrictName,

  getSelectedRegion:getSelectedRegion,

  getMapOption:getMapOption,
}
